const express = require('express');
const path = require('path');
const fs = require('fs');
const { db, initializeTables, log } = require('./dbConfig');
const cors = require('cors');

console.log('Starting index.js');

try {
  const app = express();
  app.use(express.json());

  // 动态定位 public 目录
  const publicPath = path.join(__dirname, '../public');
  console.log('Checking publicPath:', publicPath);
  if (!fs.existsSync(publicPath)) {
    log(`Public directory not found: ${publicPath}`);
    process.exit(1);
  }
  log('Serving static files from:', publicPath);
  app.use(express.static(publicPath));

  // 添加 CORS 配置
  app.use(cors({
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true
  }));

  // 路由注册
  console.log('Loading routes');
  try {
    // 首页
    app.get('/api/getPersonalScheduleCompletion', require('./homePage').getPersonalScheduleCompletion);
    app.get('/api/getDashboardStats', require('./homePage').getDashboardStats);

    // 经费管理
    app.post('/api/addFunds', require('./funds').addFunds);
    app.put('/api/updateFunds', require('./funds').updateFunds);
    app.delete('/api/deleteFunds/:id', require('./funds').deleteFunds);
    app.get('/api/getPageFundsList', require('./funds').getPageFundsList);
    app.get('/api/getFundsList', require('./funds').getFundsList);
    app.get('/api/queryFundsDetail/:id', require('./funds').queryFundsDetail);

    // 仪式厅管理
    app.post('/api/addCeremonyHall', require('./ceremonyHall').addCeremonyHall);
    app.put('/api/updateCeremonyHall', require('./ceremonyHall').updateCeremonyHall);
    app.delete('/api/deleteCeremonyHall/:id', require('./ceremonyHall').deleteCeremonyHall);
    app.get('/api/getPageCeremonyHallList', require('./ceremonyHall').getPageCeremonyHallList);
    app.get('/api/getCeremonyHallList', require('./ceremonyHall').getCeremonyHallList);
    app.get('/api/queryCeremonyHallDetail/:id', require('./ceremonyHall').queryCeremonyHallDetail);

    // 活动管理
    app.post('/api/addActivity', require('./activity').addActivity);
    app.put('/api/updateActivity', require('./activity').updateActivity);
    app.delete('/api/deleteActivity/:id', require('./activity').deleteActivity);
    app.get('/api/getPageActivityList', require('./activity').getPageActivityList);
    app.get('/api/getActivityList', require('./activity').getActivityList);
    app.get('/api/queryActivityDetail/:id', require('./activity').queryActivityDetail);

    // 档期管理
    app.post('/api/addSchedule', require('./schedule').addSchedule);
    app.put('/api/updateSchedule', require('./schedule').updateSchedule);
    app.delete('/api/deleteSchedule/:id', require('./schedule').deleteSchedule);
    app.delete('/api/batchDeleteSchedule', require('./schedule').batchDeleteSchedule);
    app.get('/api/getPageScheduleList', require('./schedule').getPageScheduleList);
    app.get('/api/getScheduleList', require('./schedule').getScheduleList);
    app.get('/api/queryScheduleDetail/:id', require('./schedule').queryScheduleDetail);
    app.post('/api/checkoutSchedule', require('./schedule').checkoutSchedule);

    // 合作人员管理
    app.post('/api/addCollaboratingPersonnel', require('./collaboratingPersonnel').addCollaboratingPersonnel);
    app.put('/api/updateCollaboratingPersonnel', require('./collaboratingPersonnel').updateCollaboratingPersonnel);
    app.delete('/api/deleteCollaboratingPersonnel/:id', require('./collaboratingPersonnel').deleteCollaboratingPersonnel);
    app.get('/api/getPageCollaboratingPersonnelList', require('./collaboratingPersonnel').getPageCollaboratingPersonnelList);
    app.get('/api/getCollaboratingPersonnelList', require('./collaboratingPersonnel').getCollaboratingPersonnelList);
    app.get('/api/queryCollaboratingPersonnelDetail/:id', require('./collaboratingPersonnel').queryCollaboratingPersonnelDetail);

    // 合作公司
    app.post('/api/addPartnerCompany', require('./partnerCompany').addPartnerCompany);
    app.put('/api/updatePartnerCompany', require('./partnerCompany').updatePartnerCompany);
    app.delete('/api/deletePartnerCompany/:id', require('./partnerCompany').deletePartnerCompany);
    app.get('/api/getPagePartnerCompanyList', require('./partnerCompany').getPagePartnerCompanyList);
    app.get('/api/getPartnerCompanyList', require('./partnerCompany').getPartnerCompanyList);
    app.get('/api/queryPartnerCompanyDetail/:id', require('./partnerCompany').queryPartnerCompanyDetail);

    // 登录
    app.post('/api/login', require('./skUserInfo').login);

    // 人员管理
    app.post('/api/addUserInfo', require('./skUserInfo').addUserInfo);
    app.put('/api/updateUserInfo', require('./skUserInfo').updateUserInfo);
    app.delete('/api/delUserinfo/:id', require('./skUserInfo').deleteUserInfo);
    app.get('/api/queryPageUserinfoList', require('./skUserInfo').getPageUserInfoList);
    app.get('/api/getUserInfoList', require('./skUserInfo').getUserInfoList);
    app.get('/api/queryUserInfoDetail/:id', require('./skUserInfo').queryUserInfoDetail);

    // 文件操作
    app.post('/api/uploadFile', require('./fileUtils').uploadFile);
    app.get('/api/downloadFile/:filename', require('./fileUtils').downloadFile);
    app.post('/api/deleteFile', require('./fileUtils').deleteFile);
    app.get('/files/:filename', require('./fileUtils').previewFile);

    log('Routes loaded successfully');
  } catch (err) {
    log(`Failed to load routes: ${err.stack}`);
    process.exit(1);
  }

  // 错误处理中间件
  app.use((err, req, res, next) => {
    log(`Express error: ${err.stack}`);
    res.status(500).json({ error: 'Internal server error' });
  });

  // 启动服务
  const PORT = process.env.PORT || 10086;
  let server;
  console.log('启动服务初始化');
  initializeTables()
    .then(() => {
      log('表结构初始化成功');
      server = app.listen(PORT, '0.0.0.0', () => {
        log(`服务正在运行 http://0.0.0.0:${PORT}`);
      }).on('error', (err) => {
        log(`Server listen error: ${err.stack}`);
        process.exit(1);
      });
    })
    .catch(err => {
      log(`表结构初始化失败: ${err.stack}`);
      process.exit(1);
    });

  // 优雅关闭
  process.on('SIGINT', () => {
    console.log('收到 SIGINT, 正在关闭服务于数据库');
    if (server) {
      server.close(() => {
        console.log('服务已关闭');
        db.close((err) => {
          if (err) {
            console.error('数据库服务关闭失败:', err.stack);
          }
          console.log('数据库服务已关闭');
          process.exit(0);
        });
      });
    } else {
      db.close((err) => {
        if (err) {
          console.error('数据库关闭失败:', err.stack);
        }
        console.log('数据库连接已关闭');
        process.exit(0);
      });
    }
  });
// 绑定信号
  ['SIGINT', 'SIGTERM'].forEach(signal => {
    process.once(signal, () => gracefulShutdown(signal));
  });

} catch (err) {
  console.error('index.js 初始化失败:', err.stack);
  process.exit(1);
}

process.on('未捕获的异常', (err) => {
  console.error(`未捕获的异常: ${err.stack}`);
  process.exit(1);
});

process.on('未捕获的异常', (reason) => {
  console.error(`未捕获的异常: ${reason.stack || reason}`);
  process.exit(1);
});